package com.xyht.sca_s.student_manage_system.modules.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.auth.entity.Node;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.*;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryBedAddMyReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryBedAddReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryBedDeletedOwnershipReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryBedUpdateReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.resp.*;
import com.xyht.sca_s.student_manage_system.modules.dormitory.mapper.*;
import com.xyht.sca_s.student_manage_system.modules.dormitory.service.SmsDormitoryBedService;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.util.NodeTreeUtil;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsUserStudentRelation;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsUserStudentRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargeCategoryDetail;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsChargePlanStudentStatus;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.StudentOrgInfoResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsChargeCategoryDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.util.CategoryItemUtil;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.util.StudentUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.dormitory.constant.IsStuConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.dormitory.constant.OrgLevelConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.dormitory.constant.OrgTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.dormitory.constant.chargeTypeConstant.CHARGE_TYPE_DORMITORY;


/**
 * <p>
 * 床号管理表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-01-08
 */
@Service
public class SmsDormitoryBedServiceImpl extends ServiceImpl<SmsDormitoryBedMapper, SmsDormitoryBed> implements SmsDormitoryBedService {

    @Resource
    private SmsDormitoryMapper dormitoryMapper;
    @Resource
    private SmsDormitoryBedMapper dormitoryBedMapper;
    @Resource
    private SmsDormitoryBuildingMapper dormitoryBuildingMapper;
    @Resource
    private SmsDormitoryFloorMapper dormitoryFloorMapper;
    @Resource
    private SmsStudentInfoMapper smsStudentInfoMapper;
    @Resource
    private SmsOrgStructureMapper orgStructureMapper;
    @Resource
    private SmsUserMapper userMapper;
    @Resource
    private SmsUserStudentRelationMapper userStudentRelationMapper;
    @Resource
    private SmsWnsChargeCategoryDetailMapper chargeCategoryDetailMapper;
    @Resource
    private SmsWnsChargeClassificationRelationMapper chargeClassificationRelationMapper;
    @Resource
    private SmsDormitoryTypeMapper dormitoryTypeMapper;
    @Resource
    private NodeTreeUtil nodeTreeUtil;
    @Resource
    private StudentUtil studentUtil;
    @Resource
    private CategoryItemUtil categoryItemUtil;

    @Override
    @Transactional
    public ResponseResult addDormitoryBed(String userId, SmsDormitoryBedAddReq addReq) {
        if (isNullOrEmpty(addReq.getBuildingId(),addReq.getFloorId(), addReq.getStuCollege(),
                addReq.getStuMajor(),addReq.getStuGrade(),addReq.getStuClass(),
                addReq.getStartDormitoryNo(), addReq.getEndDormitoryNo())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验楼栋
        SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(addReq.getBuildingId());
        if (isNullOrEmpty(smsDormitoryBuilding)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BUILDING_NOT_EXIST);
        }
        //楼层
        SmsDormitoryFloor smsDormitoryFloor = dormitoryFloorMapper.selectById(addReq.getFloorId());
        if (isNullOrEmpty(smsDormitoryFloor)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_FLOOR_NOT_EXIST);
        }
        //校验学院 专业 年级 班级
        String stuCollege = addReq.getStuCollege();
        String stuMajor = addReq.getStuMajor();
        String stuGrade = addReq.getStuGrade();
        String stuClass = addReq.getStuClass();
        SmsOrgStructure collegeOrgStructure = orgStructureMapper.selectById(stuCollege);
        if (isNullOrEmpty(collegeOrgStructure)){
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        SmsOrgStructure majorOrgStructure = orgStructureMapper.selectById(stuMajor);
        if (isNullOrEmpty(majorOrgStructure)){
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        SmsOrgStructure gradeOrgStructure = orgStructureMapper.selectById(stuGrade);
        if (isNullOrEmpty(gradeOrgStructure)){
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        SmsOrgStructure classOrgStructure = orgStructureMapper.selectById(stuClass);
        if (isNullOrEmpty(classOrgStructure)){
            return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
        }
        QueryWrapper<SmsOrgStructure> orgWrapper = new QueryWrapper<>();
        List<SmsOrgStructure> orgList = orgStructureMapper.selectList(orgWrapper);
        orgWrapper.lambda().eq(SmsOrgStructure::getOrgName, collegeOrgStructure.getOrgName());
        SmsOrgStructure collegeOrg = orgStructureMapper.selectOne(orgWrapper);
        if (collegeOrg == null) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_COLLEGE_NOT_EXIST);
        }
        List<Node> nodeList = new ArrayList<>();
        for (SmsOrgStructure structure : orgList) {
            Node node = new Node();
            BeanUtils.copyProperties(structure, node);
            nodeList.add(node);
        }
        Node collegeNode = nodeTreeUtil.getChildNodesTree(nodeList, collegeOrg.getId());
        List<Node> childNode = collegeNode.getChildNodeList();
        List<Node> majorNode = childNode.stream()
                .filter(node -> node.getOrgName().equals(majorOrgStructure.getOrgName()))
                .collect(Collectors.toList());
        if (majorNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_MAJOR_NOT_EXIST);
        }
        List<Node> gradeNode = majorNode.get(0).getChildNodeList().stream()
                .filter(node -> node.getOrgName().equals(gradeOrgStructure.getOrgName()))
                .collect(Collectors.toList());
        if (gradeNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_GRADE_NOT_EXIST);
        }
        List<Node> classNode = gradeNode.get(0).getChildNodeList().stream()
                .filter(node -> node.getOrgName().equals(classOrgStructure.getOrgName()))
                .collect(Collectors.toList());
        if (classNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_CLASS_NOT_EXIST);
        }
        //校验开始到结束房号
        SmsDormitory startDormitory = dormitoryMapper.selectById(addReq.getStartDormitoryNo());
        if (isNullOrEmpty(startDormitory)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_NOT_EXIST);
        }
        SmsDormitory endDormitory = dormitoryMapper.selectById(addReq.getEndDormitoryNo());
        if (isNullOrEmpty(endDormitory)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_NOT_EXIST);
        }
        Integer startDormitoryNumber = startDormitory.getDormitoryNumber();//开始房号
        Integer endDormitoryNumber = endDormitory.getDormitoryNumber();//结束房号
        //开始房号大于结束房号
        if (startDormitoryNumber > endDormitoryNumber) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查该楼栋 楼层下的宿舍
        List<SmsDormitory> dormitoryList = dormitoryMapper.selectList(new LambdaQueryWrapper<SmsDormitory>()
                .eq(SmsDormitory::getBuildId, addReq.getBuildingId())
                .eq(SmsDormitory::getFloorId, addReq.getFloorId()));
        if (!dormitoryList.isEmpty()) {
            List<Integer> dormitoryNumberList = dormitoryList.stream().map(SmsDormitory::getDormitoryNumber).collect(Collectors.toList());
            while (startDormitoryNumber <= endDormitoryNumber){
                if (dormitoryNumberList.contains(startDormitoryNumber)){
                    List<SmsDormitory> smsDormitoryList = dormitoryMapper.selectList(new LambdaQueryWrapper<SmsDormitory>()
                            .eq(SmsDormitory::getBuildId, addReq.getBuildingId())
                            .eq(SmsDormitory::getFloorId, addReq.getFloorId())
                            .eq(SmsDormitory::getDormitoryNumber, startDormitoryNumber));
                    if (!smsDormitoryList.isEmpty()) {
                        String dormitoryId = smsDormitoryList.get(0).getId();
                        SmsDormitoryBed smsDormitoryBed = new SmsDormitoryBed();
                        BeanUtils.copyProperties(addReq,smsDormitoryBed);
                        smsDormitoryBed.setIsOrg(IS_ORG);
                        smsDormitoryBed.setIsStu(NOT_STUDENT);
                        dormitoryBedMapper.update(smsDormitoryBed,new LambdaQueryWrapper<SmsDormitoryBed>()
                        .eq(SmsDormitoryBed::getDormitoryId,dormitoryId));
                    }
                }
                startDormitoryNumber++;
            }

        }


        return CommonResult.success();
    }



    @Override
    public ResponseResult getDormitoryBedDetail(String id) {
        if (isNullOrEmpty(id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsDormitoryBed smsDormitoryBed = dormitoryBedMapper.selectById(id);
        if (isNullOrEmpty(smsDormitoryBed)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BED_NO_EXIST);
        }

        SmsDormitoryDetailResp smsDormitoryBedDetailResp = new SmsDormitoryDetailResp();
        BeanUtils.copyProperties(smsDormitoryBed,smsDormitoryBedDetailResp);
        return CommonResult.success(smsDormitoryBedDetailResp);
    }

    @Override
    public ResponseResult updateDormitoryBed(SmsDormitoryBedUpdateReq updateReq) {
        if (isNullOrEmpty(updateReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String bedId = updateReq.getId();
        SmsDormitoryBed smsDormitoryBed = dormitoryBedMapper.selectById(bedId);
        if (isNullOrEmpty(smsDormitoryBed)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BED_NO_EXIST);
        }

        //校验学院 专业 年级 班级
        String stuCollege = updateReq.getStuCollege();
        String stuMajor = updateReq.getStuMajor();
        String stuGrade = updateReq.getStuGrade();
        String stuClass = updateReq.getStuClass();
        if(!isNullOrEmpty(stuCollege,stuMajor,stuGrade,stuClass)){
            SmsOrgStructure collegeOrgStructure = orgStructureMapper.selectById(stuCollege);
            if (isNullOrEmpty(collegeOrgStructure)){
                return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
            }
            SmsOrgStructure majorOrgStructure = orgStructureMapper.selectById(stuMajor);
            if (isNullOrEmpty(majorOrgStructure)){
                return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
            }
            SmsOrgStructure gradeOrgStructure = orgStructureMapper.selectById(stuGrade);
            if (isNullOrEmpty(gradeOrgStructure)){
                return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
            }
            SmsOrgStructure classOrgStructure = orgStructureMapper.selectById(stuClass);
            if (isNullOrEmpty(classOrgStructure)){
                return CommonResult.failed(CommonCodeEnum.ORG_NOT_EXIST);
            }

            QueryWrapper<SmsOrgStructure> orgWrapper = new QueryWrapper<>();
            List<SmsOrgStructure> orgList = orgStructureMapper.selectList(orgWrapper);
            orgWrapper.lambda().eq(SmsOrgStructure::getOrgName, collegeOrgStructure.getOrgName());
            SmsOrgStructure collegeOrg = orgStructureMapper.selectOne(orgWrapper);
            if (collegeOrg == null) {
                return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_COLLEGE_NOT_EXIST);
            }
            List<Node> nodeList = new ArrayList<>();
            for (SmsOrgStructure structure : orgList) {
                Node node = new Node();
                BeanUtils.copyProperties(structure, node);
                nodeList.add(node);
            }
            Node collegeNode = nodeTreeUtil.getChildNodesTree(nodeList, collegeOrg.getId());
            List<Node> childNode = collegeNode.getChildNodeList();
            List<Node> majorNode = childNode.stream()
                    .filter(node -> node.getOrgName().equals(majorOrgStructure.getOrgName()))
                    .collect(Collectors.toList());
            if (majorNode.size() < 1) {
                return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_MAJOR_NOT_EXIST);
            }
            List<Node> gradeNode = majorNode.get(0).getChildNodeList().stream()
                    .filter(node -> node.getOrgName().equals(gradeOrgStructure.getOrgName()))
                    .collect(Collectors.toList());
            if (gradeNode.size() < 1) {
                return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_GRADE_NOT_EXIST);
            }
            List<Node> classNode = gradeNode.get(0).getChildNodeList().stream()
                    .filter(node -> node.getOrgName().equals(classOrgStructure.getOrgName()))
                    .collect(Collectors.toList());
            if (classNode.size() < 1) {
                return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_CLASS_NOT_EXIST);
            }
            smsDormitoryBed.setIsOrg(IS_ORG);
            smsDormitoryBed.setStuClass(stuClass);
            smsDormitoryBed.setStuCollege(stuCollege);
            smsDormitoryBed.setStuGrade(stuGrade);
            smsDormitoryBed.setStuMajor(stuMajor);
        }else {
            smsDormitoryBed.setIsOrg(NOT_ORG);
            smsDormitoryBed.setIsStu(NOT_STUDENT);
            smsDormitoryBed.setStuClass("");
            smsDormitoryBed.setStuCollege("");
            smsDormitoryBed.setStuGrade("");
            smsDormitoryBed.setStuMajor("");
            smsDormitoryBed.setStuUserId("");
        }

        if (!isNullOrEmpty(updateReq.getStuUserId())) {
            String stuUserId = updateReq.getStuUserId();
            String existStuUserId = smsDormitoryBed.getStuUserId();
            if (isNullOrEmpty(existStuUserId) || !existStuUserId.equals(stuUserId)) {
                List<SmsDormitoryBed> dormitoryBedList = dormitoryBedMapper.selectList(new LambdaQueryWrapper<SmsDormitoryBed>()
                        .eq(SmsDormitoryBed::getStuUserId, stuUserId));
                if (!dormitoryBedList.isEmpty()) {
                    return CommonResult.failed(CommonCodeEnum.DORMITORY_BED_STU_EXIST);
                }
            }

            SmsUser user = userMapper.selectById(stuUserId);
            if (isNullOrEmpty(user)) {
                return CommonResult.failed(CommonCodeEnum.STUDENT_NOT_EXIST);
            }
            smsDormitoryBed.setIsStu(IS_STUDENT);
            smsDormitoryBed.setStuUserId(stuUserId);
        }

        dormitoryBedMapper.updateById(smsDormitoryBed);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getDormitoryBedList(Integer pageNum, Integer pageSize, String dormitoryId, String stuName, String stuCollege,
                                              String stuMajor, String stuGrade, String stuClass, String bedNo, String feeStandards) {
        if (isNullOrEmpty(dormitoryId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        Page<SmsDormitoryBed> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SmsDormitoryBed> dormitoryBedLambdaQueryWrapper = new LambdaQueryWrapper<SmsDormitoryBed>()
                .eq(SmsDormitoryBed::getDormitoryId,dormitoryId)
                .orderByAsc(SmsDormitoryBed::getBedNo);

//        if (!isNullOrEmpty(stuName)) {
//            List<SmsStudentInfo> smsStudentInfos = smsStudentInfoMapper.selectList(new LambdaQueryWrapper<SmsStudentInfo>()
//                    .like(SmsStudentInfo::getStuName, stuName));
//            if (!smsStudentInfos.isEmpty()) {
//                List<String> stuIdList = smsStudentInfos.stream().map(SmsStudentInfo::getId).collect(Collectors.toList());
//                dormitoryBedLambdaQueryWrapper.in(SmsDormitoryBed::getStuUserId,stuIdList);
//            }else {
//                dormitoryBedLambdaQueryWrapper.in(SmsDormitoryBed::getStuUserId,new ArrayList<>());
//            }
//
//        }
        if (!isNullOrEmpty(stuCollege)) {
            dormitoryBedLambdaQueryWrapper.eq(SmsDormitoryBed::getStuCollege,stuCollege);
        }
        if (!isNullOrEmpty(stuMajor)) {
            dormitoryBedLambdaQueryWrapper.eq(SmsDormitoryBed::getStuMajor,stuMajor);
        }
        if (!isNullOrEmpty(stuGrade)) {
            dormitoryBedLambdaQueryWrapper.eq(SmsDormitoryBed::getStuGrade,stuGrade);
        }
        if (!isNullOrEmpty(stuClass)) {
            dormitoryBedLambdaQueryWrapper.eq(SmsDormitoryBed::getStuClass,stuClass);
        }

        if (!isNullOrEmpty(feeStandards)) {
            dormitoryBedLambdaQueryWrapper.eq(SmsDormitoryBed::getStuCollege,stuCollege);
        }
        dormitoryBedMapper.selectPage(page,dormitoryBedLambdaQueryWrapper);

        List<SmsDormitoryBedDetailResp> dormitoryBedDetailList = page.getRecords()
                .stream().map(smsDormitoryBed -> {
                    SmsDormitoryBedDetailResp smsDormitoryBedDetailResp = new SmsDormitoryBedDetailResp();
                    SmsDormitoryResp smsDormitoryResp = new SmsDormitoryResp();//楼栋信息
                    SmsStudentInfoDormitoryResp studentInfoResp = new SmsStudentInfoDormitoryResp();//学生信息
                    SmsDormitory smsDormitory = dormitoryMapper.selectById(dormitoryId);
                    if (!isNullOrEmpty(smsDormitory)) {
                        BeanUtils.copyProperties(smsDormitory, smsDormitoryResp);
                        SmsDormitoryFloor dormitoryFloor = dormitoryFloorMapper.selectById(smsDormitory.getFloorId());
                        if (!isNullOrEmpty(dormitoryFloor)) {
                            smsDormitoryResp.setFloorName(dormitoryFloor.getFloorName());
                            SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(dormitoryFloor.getBuildingId());
                            if (!isNullOrEmpty(smsDormitoryBuilding)) {
                                smsDormitoryResp.setBuildingName(smsDormitoryBuilding.getBuildingName());
                                smsDormitoryResp.setBuildingDescription(smsDormitoryBuilding.getBuildingDescription());
                            }

                            //宿舍类型
                            SmsDormitoryType smsDormitoryType = dormitoryTypeMapper.selectById(smsDormitory.getDormitoryTypeId());
                            if (!isNullOrEmpty(smsDormitoryType)) {
                                //收费标准
                                List<SmsWnsChargeClassificationRelation> relationList = chargeClassificationRelationMapper.selectList(new LambdaQueryWrapper<SmsWnsChargeClassificationRelation>()
                                        .eq(SmsWnsChargeClassificationRelation::getId, smsDormitoryType.getId())
                                        .eq(SmsWnsChargeClassificationRelation::getType, CHARGE_TYPE_DORMITORY));
                                if (!relationList.isEmpty()) {
                                    String chargeDetailId = relationList.get(0).getChargeDetailId();
                                    SmsWnsChargeCategoryDetail smsWnsChargeCategoryDetail = chargeCategoryDetailMapper.selectById(chargeDetailId);
                                    if (!isNullOrEmpty(smsWnsChargeCategoryDetail)) {
                                        smsDormitoryResp.setCharge(smsWnsChargeCategoryDetail.getDefaultPrice());
                                    }

                                }

                            }
                        }
                        //学生信息
                        String userId = smsDormitoryBed.getStuUserId();
                        if (!isNullOrEmpty(userId)) {
                            SmsUser user =  userMapper.selectById(userId);
                            if (!isNullOrEmpty(user)) {
                                smsDormitoryBedDetailResp.setStuName(user.getRealName());
                            }
                        }
                        //寝室归属信息
                        SmsOrgStructureDormitoryResp collegeInfo = new SmsOrgStructureDormitoryResp();//学院
                        SmsOrgStructureDormitoryResp majorInfo = new SmsOrgStructureDormitoryResp();//专业
                        SmsOrgStructureDormitoryResp gradeInfo = new SmsOrgStructureDormitoryResp();//年级
                        SmsOrgStructureDormitoryResp classInfo = new SmsOrgStructureDormitoryResp();//班级


                        SmsOrgStructure collegeOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuCollege());
                        if (!isNullOrEmpty(collegeOrgStructure)){
                            BeanUtils.copyProperties(collegeOrgStructure,collegeInfo);
                        }
                        SmsOrgStructure majorOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuMajor());
                        if (!isNullOrEmpty(majorOrgStructure)){
                            BeanUtils.copyProperties(majorOrgStructure,majorInfo);
                        }
                        SmsOrgStructure gradeOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuGrade());
                        if (!isNullOrEmpty(gradeOrgStructure)){
                            BeanUtils.copyProperties(gradeOrgStructure,gradeInfo);
                        }
                        SmsOrgStructure classOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuClass());
                        if (!isNullOrEmpty(classOrgStructure)){
                            BeanUtils.copyProperties(classOrgStructure,classInfo);
                        }
                        smsDormitoryBedDetailResp.setId(smsDormitoryBed.getId());
                        smsDormitoryBedDetailResp.setCollegeInfo(collegeInfo);
                        smsDormitoryBedDetailResp.setMajorInfo(majorInfo);
                        smsDormitoryBedDetailResp.setGradeInfo(gradeInfo);
                        smsDormitoryBedDetailResp.setClassInfo(classInfo);
                        smsDormitoryBedDetailResp.setDormitoryInfo(smsDormitoryResp);
                        smsDormitoryBedDetailResp.setBedsNo(smsDormitoryBed.getBedNo());
                        smsDormitoryBedDetailResp.setStudentInfo(studentInfoResp);
                    }
                    return smsDormitoryBedDetailResp;
                })
                .collect(Collectors.toList());
        int total = (int)page.getTotal();
        return CommonResult.success(dormitoryBedDetailList,total);
    }

    @Override
    public ResponseResult getOrg(Integer type, Integer parentId) {
        if (isNullOrEmpty(type)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        LambdaQueryWrapper<SmsOrgStructure> orgStructureLambdaQueryWrapper = new LambdaQueryWrapper<>();
        switch (type) {
            //学院
            case COLLEGE_TYPE:
                orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, COLLEGE_PARENT_ID)
                        .eq(SmsOrgStructure::getLevel, COLLEGE_LEVEL);
                break;
            //专业
            case MAJOR_TYPE:
                orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, parentId)
                        .eq(SmsOrgStructure::getLevel, MAJOR_LEVEL);
                break;
            //年级
            case GRADE_TYPE:
                orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, parentId)
                        .eq(SmsOrgStructure::getLevel, GRADE_LEVEL);
                break;
            //班级
            case CLASS_TYPE:
                orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, parentId)
                        .eq(SmsOrgStructure::getLevel, CLASS_LEVEL);
                break;
        }
//        //学院
//        if (type == COLLEGE_TYPE) {
//            orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, COLLEGE_PARENT_ID)
//                    .eq(SmsOrgStructure::getLevel, COLLEGE_LEVEL);
//        //专业
//        } else if (type == MAJOR_TYPE) {
//            orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, parentId)
//                    .eq(SmsOrgStructure::getLevel, MAJOR_LEVEL);
//        //年级
//        } else if (type == GRADE_TYPE) {
//            orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, parentId)
//                    .eq(SmsOrgStructure::getLevel, GRADE_LEVEL);
//        //班级
//        } else if (type == CLASS_TYPE) {
//            orgStructureLambdaQueryWrapper.eq(SmsOrgStructure::getParentId, parentId)
//                    .eq(SmsOrgStructure::getLevel, CLASS_LEVEL);
//        }else {
//            return CommonResult.failed(CommonCodeEnum.FAIL);
//        }

        List<SmsDormitoryOrgStructureResp> orgStructureList = orgStructureMapper.selectList(orgStructureLambdaQueryWrapper)
                .stream()
                .map(smsOrgStructure -> {
                    SmsDormitoryOrgStructureResp smsDormitoryOrgStructureResp = new SmsDormitoryOrgStructureResp();
                    BeanUtils.copyProperties(smsOrgStructure,smsDormitoryOrgStructureResp);
                    return smsDormitoryOrgStructureResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(orgStructureList);
    }

    @Override
    public ResponseResult deletedDormitoryOwnership(SmsDormitoryBedDeletedOwnershipReq deletedOwnershipReq) {
        if (isNullOrEmpty(deletedOwnershipReq.getBuildingId(),deletedOwnershipReq.getFloorId(),
                deletedOwnershipReq.getStartDormitoryNo(),deletedOwnershipReq.getEndDormitoryNo())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验楼栋
        SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(deletedOwnershipReq.getBuildingId());
        if (isNullOrEmpty(smsDormitoryBuilding)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BUILDING_NOT_EXIST);
        }
        //楼层
        SmsDormitoryFloor smsDormitoryFloor = dormitoryFloorMapper.selectById(deletedOwnershipReq.getFloorId());
        if (isNullOrEmpty(smsDormitoryFloor)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_FLOOR_NOT_EXIST);
        }
        //校验开始到结束房号
        SmsDormitory startDormitory = dormitoryMapper.selectById(deletedOwnershipReq.getStartDormitoryNo());
        if (isNullOrEmpty(startDormitory)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_NOT_EXIST);
        }
        SmsDormitory endDormitory = dormitoryMapper.selectById(deletedOwnershipReq.getEndDormitoryNo());
        if (isNullOrEmpty(endDormitory)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_NOT_EXIST);
        }
        Integer startDormitoryNumber = startDormitory.getDormitoryNumber();//开始房号
        Integer endDormitoryNumber = endDormitory.getDormitoryNumber();//结束房号
        //开始房号大于结束房号
        if (startDormitoryNumber > endDormitoryNumber) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查该楼栋 楼层下的宿舍
        List<SmsDormitory> dormitoryList = dormitoryMapper.selectList(new LambdaQueryWrapper<SmsDormitory>()
                .eq(SmsDormitory::getBuildId, deletedOwnershipReq.getBuildingId())
                .eq(SmsDormitory::getFloorId, deletedOwnershipReq.getFloorId()));
        if (dormitoryList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_NOT_EXIST);
        }

        List<Integer> dormitoryNumberList = dormitoryList.stream().map(SmsDormitory::getDormitoryNumber).collect(Collectors.toList());
        while (startDormitoryNumber <= endDormitoryNumber) {
            if (dormitoryNumberList.contains(startDormitoryNumber)) {
                List<SmsDormitory> smsDormitoryList = dormitoryMapper.selectList(new LambdaQueryWrapper<SmsDormitory>()
                        .eq(SmsDormitory::getBuildId, deletedOwnershipReq.getBuildingId())
                        .eq(SmsDormitory::getFloorId, deletedOwnershipReq.getFloorId())
                        .eq(SmsDormitory::getDormitoryNumber, startDormitoryNumber));
                if (!smsDormitoryList.isEmpty()) {
                    String dormitoryId = smsDormitoryList.get(0).getId();
                    SmsDormitoryBed smsDormitoryBed = new SmsDormitoryBed();
                    BeanUtils.copyProperties(deletedOwnershipReq, smsDormitoryBed);
                    smsDormitoryBed.setIsOrg(NOT_ORG);
                    smsDormitoryBed.setStuUserId("");
                    smsDormitoryBed.setStuCollege("");
                    smsDormitoryBed.setStuMajor("");
                    smsDormitoryBed.setStuGrade("");
                    smsDormitoryBed.setStuClass("");
                    smsDormitoryBed.setIsStu(NOT_STUDENT);
                    dormitoryBedMapper.update(smsDormitoryBed, new LambdaQueryWrapper<SmsDormitoryBed>()
                            .eq(SmsDormitoryBed::getDormitoryId, dormitoryId));
                }
            }
            startDormitoryNumber++;
        }

        return CommonResult.success();
    }

    @Override
    public ResponseResult getMyDormitoryBed(String userId) {
        SmsDormitoryBedDetailResp smsDormitoryBedDetailResp = new SmsDormitoryBedDetailResp();

        //床位信息
        List<SmsDormitoryBed> dormitoryBedList = dormitoryBedMapper.selectList(new LambdaQueryWrapper<SmsDormitoryBed>()
                .eq(SmsDormitoryBed::getStuUserId, userId));
        if (dormitoryBedList.isEmpty()) {
          return CommonResult.success(smsDormitoryBedDetailResp);
        }

        SmsDormitoryBed smsDormitoryBed = dormitoryBedList.get(0);
        SmsDormitoryResp smsDormitoryResp = new SmsDormitoryResp();//楼栋信息
        SmsStudentInfoDormitoryResp studentInfoResp = new SmsStudentInfoDormitoryResp();//学生信息

        //学生信息
        List<SmsUserStudentRelation> relations = userStudentRelationMapper.selectList(new LambdaQueryWrapper<SmsUserStudentRelation>().eq(SmsUserStudentRelation::getUserId, userId));
        if (relations.isEmpty()) {
            return CommonResult.success(smsDormitoryBedDetailResp);
        }

        String stuId = relations.get(0).getStuId();
        SmsStudentInfo smsStudentInfo = smsStudentInfoMapper.selectById(stuId);
        if (!isNullOrEmpty(smsStudentInfo)) {
            BeanUtils.copyProperties(smsStudentInfo, studentInfoResp);
        }
        //宿舍信息
        SmsDormitory smsDormitory = dormitoryMapper.selectById(smsDormitoryBed.getDormitoryId());
        if (isNullOrEmpty(smsDormitory)) {
            return CommonResult.success(smsDormitoryBedDetailResp);
        }

        //楼层信息
        SmsDormitoryFloor dormitoryFloor = dormitoryFloorMapper.selectById(smsDormitory.getFloorId());
        if (isNullOrEmpty(dormitoryFloor)) {
            return CommonResult.success(smsDormitoryBedDetailResp);
        }
        //楼栋信息
        SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(dormitoryFloor.getBuildingId());
        if (isNullOrEmpty(smsDormitoryBuilding)) {
            return CommonResult.success(smsDormitoryBedDetailResp);
        }

        //寝室归属信息
        SmsOrgStructureDormitoryResp collegeInfo = new SmsOrgStructureDormitoryResp();//学院
        SmsOrgStructureDormitoryResp majorInfo = new SmsOrgStructureDormitoryResp();//专业
        SmsOrgStructureDormitoryResp gradeInfo = new SmsOrgStructureDormitoryResp();//年级
        SmsOrgStructureDormitoryResp classInfo = new SmsOrgStructureDormitoryResp();//班级


        SmsOrgStructure collegeOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuCollege());
        if (!isNullOrEmpty(collegeOrgStructure)) {
            BeanUtils.copyProperties(collegeOrgStructure, collegeInfo);
        }
        SmsOrgStructure majorOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuMajor());
        if (!isNullOrEmpty(majorOrgStructure)) {
            BeanUtils.copyProperties(majorOrgStructure, majorInfo);
        }
        SmsOrgStructure gradeOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuGrade());
        if (!isNullOrEmpty(gradeOrgStructure)) {
            BeanUtils.copyProperties(gradeOrgStructure, gradeInfo);
        }
        SmsOrgStructure classOrgStructure = orgStructureMapper.selectById(smsDormitoryBed.getStuClass());
        if (!isNullOrEmpty(classOrgStructure)) {
            BeanUtils.copyProperties(classOrgStructure, classInfo);
        }

        BeanUtils.copyProperties(smsDormitory, smsDormitoryResp);
        smsDormitoryResp.setFloorName(dormitoryFloor.getFloorName());
        smsDormitoryResp.setBuildingName(smsDormitoryBuilding.getBuildingName());

        smsDormitoryBedDetailResp.setId(smsDormitoryBed.getId());
        smsDormitoryBedDetailResp.setCollegeInfo(collegeInfo);
        smsDormitoryBedDetailResp.setMajorInfo(majorInfo);
        smsDormitoryBedDetailResp.setGradeInfo(gradeInfo);
        smsDormitoryBedDetailResp.setClassInfo(classInfo);
        smsDormitoryBedDetailResp.setDormitoryInfo(smsDormitoryResp);
        smsDormitoryBedDetailResp.setBedsNo(smsDormitoryBed.getBedNo());
        smsDormitoryBedDetailResp.setStudentInfo(studentInfoResp);
        //宿舍价格
        List<SmsWnsChargeClassificationRelation> classificationRelations = chargeClassificationRelationMapper.selectList(new LambdaQueryWrapper<SmsWnsChargeClassificationRelation>()
                .eq(SmsWnsChargeClassificationRelation::getType, CHARGE_TYPE_DORMITORY)
                .eq(SmsWnsChargeClassificationRelation::getClassificationId, smsDormitory.getDormitoryTypeId()));
        if (!classificationRelations.isEmpty()) {
            String chargeDetailId = classificationRelations.get(0).getChargeDetailId();
            SmsWnsChargeCategoryDetail chargeCategoryDetail = chargeCategoryDetailMapper.selectAllById(chargeDetailId);
            if (!isNullOrEmpty(chargeCategoryDetail)) {
                SmsWnsChargePlanStudentStatus status = categoryItemUtil.getStatusByCategoryDetailName(userId, chargeCategoryDetail.getName());
                smsDormitoryBedDetailResp.setStatus(status);
            }

        }

        return CommonResult.success(smsDormitoryBedDetailResp);
    }

    @Override
    public ResponseResult chooseDormitoryList(Integer pageNum, Integer pageSize, String userId) {
        Page<SmsDormitoryBed> page = new Page<>(pageNum,pageSize);
        SmsChooseDormitoryResp smsChooseDormitoryResp = new SmsChooseDormitoryResp();
        //学生的院系 专业 年级 班级信息
        StudentOrgInfoResp studentCollegeMajorClassInfo = studentUtil.getStudentCollegeMajorClassInfo(userId);
        if (isNullOrEmpty(studentCollegeMajorClassInfo)) {
            return CommonResult.success(smsChooseDormitoryResp);
        }
        String collegeId = studentCollegeMajorClassInfo.getCollegeId();
        String majorId = studentCollegeMajorClassInfo.getMajorId();
        String gradeId = studentCollegeMajorClassInfo.getGradeId();
        String classId = studentCollegeMajorClassInfo.getClassId();
        List<String> dormitoryIdList = dormitoryBedMapper.selectList(new LambdaQueryWrapper<SmsDormitoryBed>()
                .eq(SmsDormitoryBed::getStuCollege, collegeId)
                .eq(SmsDormitoryBed::getStuMajor, majorId)
                .eq(SmsDormitoryBed::getStuGrade, gradeId)
                .eq(SmsDormitoryBed::getStuClass, classId))
                .stream()
                .map(SmsDormitoryBed::getDormitoryId).collect(Collectors.toList());
        if (dormitoryIdList.isEmpty()) {
            return CommonResult.success(smsChooseDormitoryResp);
        }
        List<String> filterDormitoryIdList = dormitoryIdList.stream().distinct().collect(Collectors.toList());
        //学生学院 专业 年级 班级
        smsChooseDormitoryResp.setCollegeId(studentCollegeMajorClassInfo.getCollegeId());
        smsChooseDormitoryResp.setCollegeName(studentCollegeMajorClassInfo.getCollegeName());
        smsChooseDormitoryResp.setMajorId(studentCollegeMajorClassInfo.getMajorId());
        smsChooseDormitoryResp.setMajorName(studentCollegeMajorClassInfo.getMajorName());
        smsChooseDormitoryResp.setGradeId(studentCollegeMajorClassInfo.getGradeId());
        smsChooseDormitoryResp.setGradeName(studentCollegeMajorClassInfo.getGradeName());
        smsChooseDormitoryResp.setClassId(studentCollegeMajorClassInfo.getClassId());
        smsChooseDormitoryResp.setClassName(studentCollegeMajorClassInfo.getClassName());
        //宿舍信息
        List<SmsDormitoryResp> dormitoryList = filterDormitoryIdList.stream().map(dormitoryId -> {
            //宿舍信息
            SmsDormitoryResp smsDormitoryResp = new SmsDormitoryResp();
            SmsDormitory smsDormitory = dormitoryMapper.selectById(dormitoryId);
            BeanUtils.copyProperties(smsDormitory,smsDormitoryResp);
            if (!isNullOrEmpty(smsDormitory)) {
                BeanUtils.copyProperties(smsDormitory, smsDormitoryResp);
                SmsDormitoryFloor dormitoryFloor = dormitoryFloorMapper.selectById(smsDormitory.getFloorId());
                if (!isNullOrEmpty(dormitoryFloor)) {
                    smsDormitoryResp.setFloorName(dormitoryFloor.getFloorName());
                    SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(dormitoryFloor.getBuildingId());
                    if (!isNullOrEmpty(smsDormitoryBuilding)) {
                        smsDormitoryResp.setBuildingName(smsDormitoryBuilding.getBuildingName());
                    }
                }
                //宿舍价格
                List<SmsWnsChargeClassificationRelation> classificationRelations = chargeClassificationRelationMapper.selectList(new LambdaQueryWrapper<SmsWnsChargeClassificationRelation>()
                        .eq(SmsWnsChargeClassificationRelation::getType, CHARGE_TYPE_DORMITORY)
                        .eq(SmsWnsChargeClassificationRelation::getClassificationId, smsDormitory.getDormitoryTypeId()));
                if (!classificationRelations.isEmpty()) {
                    String chargeDetailId = classificationRelations.get(0).getChargeDetailId();
                    SmsWnsChargeCategoryDetail chargeCategoryDetail = chargeCategoryDetailMapper.selectAllById(chargeDetailId);
                    if (!isNullOrEmpty(chargeCategoryDetail)) {
                        SmsWnsChargePlanStudentStatus status = categoryItemUtil.getStatusByCategoryDetailName(userId, chargeCategoryDetail.getName());
                        smsDormitoryResp.setStatus(status);
                    } else {
                        smsDormitoryResp.setStatus(null);
                    }

                }else {
                    smsDormitoryResp.setStatus(null);
                }
            }
            List<SmsDormitoryBedDetailResp> dormitoryBedDetailList = dormitoryBedMapper.selectList(new LambdaQueryWrapper<SmsDormitoryBed>()
                    .eq(SmsDormitoryBed::getDormitoryId, dormitoryId))
                    .stream()
                    .map(smsDormitoryBed -> {
                        SmsDormitoryBedDetailResp smsDormitoryBedDetailResp = new SmsDormitoryBedDetailResp();
                        BeanUtils.copyProperties(smsDormitoryBed, smsDormitoryBedDetailResp);
                        String stuCollege = smsDormitoryBed.getStuCollege();
                        String stuMajor = smsDormitoryBed.getStuMajor();
                        String stuGrade = smsDormitoryBed.getStuGrade();
                        String stuClass = smsDormitoryBed.getStuClass();
                        if (stuCollege.equals(collegeId) && stuMajor.equals(majorId) && stuGrade.equals(gradeId) && stuClass.equals(classId)) {
                            if (smsDormitoryBed.getIsStu() == 0) {
                                smsDormitoryBedDetailResp.setIsChoose(0);
                            }else {
                                smsDormitoryBedDetailResp.setIsChoose(1);
                            }

                        }else {
                            smsDormitoryBedDetailResp.setIsChoose(1);
                        }

//                                //宿舍类型
//                                SmsDormitoryType smsDormitoryType = dormitoryTypeMapper.selectById(smsDormitory.getDormitoryTypeId());
//                                if (!isNullOrEmpty(smsDormitoryType)) {
//                                    //收费标准
//                                    List<SmsWnsChargeClassificationRelation> relations = chargeClassificationRelationMapper.selectList(new LambdaQueryWrapper<SmsWnsChargeClassificationRelation>()
//                                            .eq(SmsWnsChargeClassificationRelation::getId, smsDormitoryType.getId())
//                                            .eq(SmsWnsChargeClassificationRelation::getType, CHARGE_TYPE_DORMITORY));
//                                    if (!relations.isEmpty()) {
//                                        String chargeDetailId = relations.get(0).getChargeDetailId();
//                                        SmsWnsChargeCategoryDetail smsWnsChargeCategoryDetail = chargeCategoryDetailMapper.selectById(chargeDetailId);
//                                        if (!isNullOrEmpty(smsWnsChargeCategoryDetail)) {
//                                            smsDormitoryResp.setCharge(smsWnsChargeCategoryDetail.getDefaultPrice());
//                                        }
//
//                                    }
//                                }

//                            smsDormitoryBedDetailResp.setIsStu(smsDormitoryBed.getIsStu());
                            smsDormitoryBedDetailResp.setBedsNo(smsDormitoryBed.getBedNo());
                        return smsDormitoryBedDetailResp;
                    })
                    .collect(Collectors.toList());
            smsDormitoryResp.setBedDetailList(dormitoryBedDetailList);

            return smsDormitoryResp;
        }).collect(Collectors.toList());
        smsChooseDormitoryResp.setDormitoryDetailList(dormitoryList);

        int total = (int) page.getTotal();
        return CommonResult.success(smsChooseDormitoryResp, total);
    }

    @Override
    public ResponseResult addMyDormitoryBed(SmsDormitoryBedAddMyReq addMyReq, String userId) {
        if (isNullOrEmpty(addMyReq.getDormitoryBedId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验自己是否已选择了宿舍
        List<SmsDormitoryBed> dormitoryBedList = dormitoryBedMapper.selectList(new LambdaQueryWrapper<SmsDormitoryBed>()
                .eq(SmsDormitoryBed::getStuUserId, userId));
        if (!dormitoryBedList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BED_STUDENT_NOT_REPEAT);
        }
        SmsDormitoryBed smsDormitoryBed = dormitoryBedMapper.selectById(addMyReq.getDormitoryBedId());
        if (isNullOrEmpty(smsDormitoryBed)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BED_NO_EXIST);
        }
        //校验宿舍是否被占用了
        Integer isStu = smsDormitoryBed.getIsStu();
        String stuUserId = smsDormitoryBed.getStuUserId();
        if (isStu == IS_STUDENT || !isNullOrEmpty(stuUserId)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BED_STUDENT_EXIST);
        }
        smsDormitoryBed.setIsStu(IS_STUDENT);
        smsDormitoryBed.setStuUserId(userId);
        dormitoryBedMapper.updateById(smsDormitoryBed);
        return CommonResult.success();
    }


}
